package cn.exrick.xboot.common.jiuqiCommon.callAPIUtil;


import cn.exrick.xboot.common.utils.SpringUtils;
import cn.exrick.xboot.modules.ApprovalInfo.entity.ApprovalInfo;
import cn.exrick.xboot.modules.httpMAS.config.SMSConfig;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * njp 调用对接子系统的工具类 20190813
 */
@Slf4j
public class CallApiUtil {
    public static JSONObject doPost(JSONObject date, String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        //HttpClient client =
        // 要调用的接口方法
        //String url = "http://10.39.5.48:9797/portal/GetWorkFlowServlet";
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            StringEntity s = new StringEntity(date.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "text/xml");
            CloseableHttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonObject;
    }

    public  JSONObject javaToJSON() {
       /*
       //1.
       System.out.println("java代码封装为json字符串");
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("username", "张三");
        Map map = new HashMap();
        map.put("receiver", "JQFO");
        map.put("data", "test");
        jsonObj.put("data", map);
        System.out.println("java--->json \n" + jsonObj.toString());*/

       //2.
       /* ApprovalInfo  approvalInfo=new ApprovalInfo();
        approvalInfo.setId("123456789");
        approvalInfo.setApprovalStatus(3);
        approvalInfo.setNowTime(new Date());



        System.out.println("java代码封装为json字符串");
        JSONObject jsonObj = new JSONObject();
        Map map = new HashMap();
        map.put("success", "true");
        map.put("code", "200");
        map.put("result", approvalInfo);
        jsonObj.put("data", map);
        System.out.println("java--->json \n" + jsonObj.toString());*/

       //3.
     /*   ApprovalInfo  approvalInfo=new ApprovalInfo();
        approvalInfo.setId("123456789");
        approvalInfo.setApprovalStatus(3);
        approvalInfo.setNowTime(new Date());

        System.out.println("java代码封装为json字符串");
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("success", "true");
        jsonObj.put("code", "200");
        jsonObj.put("message", "审批成功");
        jsonObj.put("result", approvalInfo);
        System.out.println("java--->json \n" + jsonObj.toString());*/

     //4
        JSONObject jsonObj = new JSONObject();
        List<UserTest> users=new ArrayList<>();
        Multimap<String, String> maps = LinkedHashMultimap.create();
        for (int i = 0; i <3 ; i++) {
            //maps.put("usercode",getRandom4(13));
            UserTest ut=new UserTest(getRandom4(13));
            users.add(ut);
        }
        jsonObj.put("datats", users);
        log.info(jsonObj.toString());
        return jsonObj;
    }

    public static String getRandom4(int len) {
                 String source = "0123456789";
                 Random r = new Random();
                 StringBuilder rs = new StringBuilder();
                 for (int j = 0; j < len; j++) {
                         rs.append(source.charAt(r.nextInt(10)));
                     }
                 return rs.toString();
            }


    public static Object doForm(JSONObject jsonObject, String url) throws Exception {
        //String url = "xxx.xxx.xxx";
        JSONObject  backInfo=null;
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //post表单
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();

        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
        post.setEntity(urlEncodedFormEntity);
        HttpResponse res = client.execute(post);
        String response1 = EntityUtils.toString(res.getEntity());
        //HttpEntity entity = res.getEntity();
        System.out.println(response1);
     /*   if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if(CallApiUtil.isJson(response1)){
                backInfo = JSONObject.parseObject(response1);
            }
        }*/
        return response1;
    }

    public static boolean isJson(String content) {
        try {
            JSONObject jsonStr = JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public JSONObject doPostGetJson(JSONObject json, String url) throws Exception {
        JSONObject sr = this.doPost(json, url);
        log.info(json.toString());
        System.out.println("返回参数：" + sr);
        //return sr.toString();
        return sr;
    }


    /*
     * HttpClient Get请求带参数
     */

    public static String fun1(String  url) throws ClientProtocolException, IOException {

//		1、创建httpClient
        CloseableHttpClient client = HttpClients.createDefault();
//		2、封装请求参数
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
       /* list.add(new BasicNameValuePair("userCode", "3974FBE7EEA5A80BE22F8D01268A2BD5FA2E5C4E1B5DF3B9"));
        list.add(new BasicNameValuePair("templateName", "GTMC_FPYJCX22"));*/

        //3、转化参数
        String params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        System.out.println("封装请求参数"+params);
        //4、创建HttpGet请求
        //HttpGet httpGet = new HttpGet("http://10.39.5.48:9797/portal/sso"+"?"+params);
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = client.execute(httpGet);


        //5、获取实体
        HttpEntity entity = response.getEntity();
        //将实体装成字符串
        String string = EntityUtils.toString(entity);
        System.out.println(string);

        response.close();
        return string;
    }

    /**
     * 组装重定向子系统（单点登录）的链接
     * @param
     */
    public static String callRedirect(JSONObject jsonObject, String url,HttpServletResponse response)  {
        //封装请求参数
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
       // list.add(new BasicNameValuePair("templateName", "GTMC_FPYJCX22"));
        //转化参数
        String params = null;
        String rediRecturl=null;
        try {
            params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        System.out.println("封装请求参数"+params);

        //重定向地址
         rediRecturl=url+"?"+params;
        response.sendRedirect(rediRecturl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rediRecturl;
    }

    class UserTest{
        private String usercode;

        public String getUsercode() {
            return usercode;
        }

        public void setUsercode(String usercode) {
            this.usercode = usercode;
        }

        public   UserTest(String usercode){
          this.usercode=usercode;
      }
    }
    public static void main(String[] args) {

          // CallApiUtil.callRedirect();
        new CallApiUtil().javaToJSON();
    }

}
